#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdint.h>

//校验和计算
uint8_t msg_xor_check(uint8_t* s, uint32_t len) {
	uint8_t temp = s[0];
	uint32_t i = 0;
	for (i = 1; i < len; i++) {
		temp ^= s[i];
	}
	return temp;
}

//unsigned char XorCheckSumInString__(char *s, uint32_t start, uint32_t length) {
//	uint32_t i;
//	//res是最终的异或结果计算返回值
//	unsigned char b, res;
//	res = 0;
//	for (i = 0; i < length; i++) {
//		//s是字符串接受缓冲器的首地址
//		b  = (unsigned char)s[i + start];
//		//start是需要处理的字符串首地址偏移量
//		res ^= b;
//	}
//	return res;
//}

//计算文件大小
int file_size(char* filename) {
	//获取文件名为filename的文件大小。
	FILE *fp = fopen(filename, "rb");//打开文件。
	int size;
	if (fp == NULL) 		// 打开文件失败
		return -1;
	fseek(fp, 0, SEEK_END);	//定位文件指针到文件尾。
	size = ftell(fp); 		//获取文件指针偏移量，即文件大小。
	fclose(fp);				//关闭文件。
	return size;
}

int main(int argc, char *argv[]) {
	char *SfileName = "E:\\ApplicationData.s19";
	int SfileSize = file_size(SfileName);
	printf("Sfile size is : 0X%08x\n", SfileSize);
	uint32_t SfileXor = msg_xor_check(SfileName, SfileSize);
	printf("SfileXor check is: 0X%08x\n", SfileXor);
	printf("===============================\n");

	char *buf;
	char *ident;
	unsigned int i, file_size, need_comma;
	FILE *file_input, *file_output;
	if (argc < 4) {
		fprintf(stderr, "Usage: %s binary_file output_file array_name\n", argv[0]);
		return -1;
	}
	file_input = fopen(argv[1], "rb");
	if (file_input == NULL) {
		fprintf(stderr, "%s: cant open %s for reading!\n", argv[0], argv[1]);
		return -1;
	}
	//得到file长度
	fseek(file_input, 0, SEEK_END);
	file_size = ftell(file_input);
	fseek(file_input, 0, SEEK_SET);
	buf = (char *)malloc(file_size);
	assert(buf);
	fread(buf, file_size, 1, file_input);
	fclose(file_input);

	file_output = fopen(argv[2], "w");
	if (file_output == NULL) {
		fprintf(stderr, "%s: can't open %s for writing\n", argv[0], argv[2]);
		return -1;
	}
	ident = argv[3];
	need_comma = 0;
	fprintf(file_output, "const char %s[%i] = {", ident, file_size);
	for (i = 0; i < file_size; i++) {
		if (need_comma)
			fprintf(file_output, ", ");
		else
			need_comma = 1;
		if ((i % 11) == 0)
			fprintf(file_output, "\n\t");
		fprintf(file_output, "0x%.2x", buf[i] & 0xff);
	}
	fprintf(file_output, "\n};\n\n");
	fprintf(file_output, "const int %s_length = %i;\n", ident, file_size);
	fclose(file_output);
	return 0;
}
